﻿import Hobot.GPIO as GPIO
import time

def read_dht11_dat():
    DHT11_PIN = 11  # 设置连接DHT11数据线的GPIO引脚号
    GPIO.setmode(GPIO.BOARD)  # 使用物理引脚编号
    GPIO.setup(DHT11_PIN, GPIO.OUT)
    GPIO.output(DHT11_PIN, GPIO.LOW)
    time.sleep(0.02)
    GPIO.output(DHT11_PIN, GPIO.HIGH)
    time.sleep(0.00002)
    GPIO.setup(DHT11_PIN, GPIO.IN)

    data = []
    count = 0

    # 等待DHT11响应
    while GPIO.input(DHT11_PIN) == GPIO.LOW:
        continue

    while GPIO.input(DHT11_PIN) == GPIO.HIGH:
        continue

    for i in range(0, 40):
        k = 0
        while GPIO.input(DHT11_PIN) == GPIO.LOW:
            continue

        while GPIO.input(DHT11_PIN) == GPIO.HIGH:
            k += 1
            if k > 100:
                break

        if k < 8:
            data.append(0)
        else:
            data.append(1)

    humidity_bit = data[0:8]  # 湿度位
    temperature_bit = data[16:24]  # 温度位
    humidity = 0
    temperature = 0

    for i in range(8):
        humidity += humidity_bit[i] * 2 ** (7 - i)
        temperature += temperature_bit[i] * 2 ** (7 - i)

    print("DEBUG: Data read from DHT11 - Humidity bits: {}, Temperature bits: {}".format(humidity_bit, temperature_bit))
    return humidity, temperature

if __name__ == '__main__':
    print("Starting DHT11 data read loop...")
    try:
        while True:
            humidity, temperature = read_dht11_dat()
            print("Humidity: {}%, Temperature: {} C".format(humidity, temperature))
            time.sleep(2)  # 读取间隔，根据需要调整
    except KeyboardInterrupt:
        print("Program stopped by user.")
        GPIO.cleanup()
    except Exception as e:
        print(f"An error occurred: {e}")
        GPIO.cleanup()
